package turtle.system.pt;

import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.TreeMap;

import turtle.daily.TaifexCrawler;
import turtle.system.util.techindex.ADXIndex;

import arbor.mining.util.date.DateUtil;
import arbor.mining.util.net.WebStringConn;
import arbor.mining.util.stock.CNYesGather;
import arbor.mining.util.stock.DBMakerGather;
import arbor.mining.util.stock.StockEntity;

/**
 * 丁彬系統
 * @author doug
 *
 */
public class DailyExec {

	public static final String WTX0_PREFIX_FN = "data/1000-update";
	public static final String WTX1_PREFIX_FN = "data/future-update";
    
	public static final String FN_SUFFIX = ".txt";

	public static final String WTX0_HISTORY_FN = "data/WTX0_history.txt";
	public static final String WTX1_HISTORY_FN = "data/WTX1_history.txt";
	public static final String WTX1_WORD = "WTX1 台指期貨\n\n日期 	開盤 	最高 	最低 	收盤 	成交量\n";
	public static final String WTX0_WORD = "1000 加權\n\n日期 	開盤 	最高 	最低 	收盤 	成交量\n";
	public static final String CONS_PROFIT_HISTOGRAM_FN = "tmp/consprofit_hist.csv";
	public static final String POSI_PROFIT_HISTOGRAM_FN = "tmp/posiprofit_hist.csv";
	
	private static final int TYPE_TW1000 = 1;
	private static final int TYPE_TWX1 = 2;
	Properties urlProp;

	private void setupURLProperties() {
		urlProp = new Properties();
		try {
			urlProp
					.load(DailyExec.class.getClassLoader()
							.getResourceAsStream(
									"turtle/system/pt/stock.properties"));
		} catch (IOException e) {
			System.out.println(e);
		}
	}

	public void getHistory() {

		DBMakerGather gather = new DBMakerGather();
		ArrayList<StockEntity> list = new ArrayList<StockEntity>();

		WebStringConn conn = new WebStringConn(null);
		list = new TaifexCrawler().getHistory();
		String fn = WTX1_HISTORY_FN;
		historySave2File(list, fn, TYPE_TWX1);

		list.clear();
		String content = conn.getAllTableContent(urlProp
				.getProperty("WTX0_HISTORY_URL"), true, true);
		gather.parseHistoryEntity(list, content);
		fn = WTX0_HISTORY_FN;
		historySave2File(list, fn, TYPE_TW1000);
	}

	public DailyExec(boolean getHistory) throws IOException {
		setupURLProperties();
		ArrayList<Double> consProfitValues = null;
		ArrayList<Double> posiProfitValues = null;
		if (!getHistory) {
			DateFormat df = new SimpleDateFormat("yyyyMMdd");
			Date today = DateUtil.getCurrentDate();

			DBMakerGather gather = new DBMakerGather();
			StockEntity wtx0 = gather.getTodayIndexPrice(DBMakerGather.WTX0_ID);
			StockEntity wtx1 = gather.getTodayIndexPrice(DBMakerGather.WTX1_ID);
			//CNYesGather gather = new CNYesGather();
			//StockEntity[] wtx = gather.getInstantWTXPrice();
			//StockEntity wtx0 = wtx[0];
			//StockEntity wtx1 = wtx[1];
			String fn;
			if (wtx1!=null) {
			  fn = WTX1_PREFIX_FN + FN_SUFFIX;
			  dailySave2File(wtx1, fn, TYPE_TWX1);
			}
			if (wtx0!=null) { 
			  fn = WTX0_PREFIX_FN + FN_SUFFIX;
			  dailySave2File(wtx0, fn, TYPE_TW1000);
			}
		} else {
			this.getHistory();
		}
		
		PriceData cons = new PriceData(PriceData.STRATEGY_CONSERVATIVE,
				DailyExec.WTX0_PREFIX_FN + DailyExec.FN_SUFFIX,
				DailyExec.WTX1_PREFIX_FN + DailyExec.FN_SUFFIX);
		String consSum = cons.getSummary();
		String conservative = cons.getFinalSuggestion();
		consProfitValues = cons.getProfitStat().valueList;
		
		PriceData post = new PriceData(PriceData.STRATEGY_POSITIVE,
				DailyExec.WTX0_PREFIX_FN + DailyExec.FN_SUFFIX,
				DailyExec.WTX1_PREFIX_FN + DailyExec.FN_SUFFIX);

		String postSum = post.getSummary();
		String positive = post.getFinalSuggestion();
		posiProfitValues = post.getProfitStat().valueList;
		
		StringBuffer buf = new StringBuffer();
		buf.append("保守建議:\n" + conservative+"\n");		
		buf.append("保守策略Summary:\n" + consSum+"\n");
		buf.append("積極建議:\n" + positive+"\n");
		buf.append("積極策略Summary:\n" + postSum+"\n");		
		System.out.println("=====================\n"+buf.toString());
		
		try {
			BufferedWriter writer1 = new BufferedWriter(new FileWriter(CONS_PROFIT_HISTOGRAM_FN));
			BufferedWriter writer2 = new BufferedWriter(new FileWriter(POSI_PROFIT_HISTOGRAM_FN));
			for (int i=0;i<consProfitValues.size();i++) {
				writer1.write(consProfitValues.get(i)+"\n");
			}
			for (int i=0;i<posiProfitValues.size();i++) {
				writer2.write(posiProfitValues.get(i)+"\n");
			}
			writer1.close();
			writer2.close();
		}
		catch (IOException e) {
			System.out.println(e);
		}
		
	}

	private static void copyFile(String srcFN, String destFN) {
		try {
			File inputFile = new File(srcFN);
			File outputFile = new File(destFN);

			FileReader in = new FileReader(inputFile);
			FileWriter out = new FileWriter(outputFile);
			int c;

			while ((c = in.read()) != -1)
				out.write(c);

			in.close();
			out.close();
		} catch (IOException e) {
			System.out.println(e);
		}
	}
    public static TreeMap<String, StockEntity> getAllStockData(String fn) {
		DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		TreeMap<String, StockEntity> entities = new TreeMap<String, StockEntity>();
		ArrayList<String> dayList1 = new ArrayList<String>();
		ArrayList<String> dayList = new ArrayList<String>();
		ArrayList<StockEntity> seList = new ArrayList<StockEntity>();
		try {
			BufferedReader reader = new BufferedReader(new FileReader(fn));
			reader.readLine();
			reader.readLine();
			reader.readLine();
			String line;
			while ((line = reader.readLine()) != null) {
				StockEntity en = StockEntity.parseEntity(line);
				seList.add(en);
				entities.put(df.format(en.startTime.getTime()), en);
			}

			reader.close();
		} catch (IOException e) {
			System.out.println(e);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ADXIndex.attachIndex4StockEntity(seList);
		return entities;
    }
	private void dailySave2File(StockEntity entity, String fileName, int type) {
		DateFormat df = new SimpleDateFormat("yyyy/MM/dd");

		ArrayList<String> dayList1 = new ArrayList<String>();
		ArrayList<String> dayList = new ArrayList<String>();
		try {
			BufferedReader reader = new BufferedReader(new FileReader(fileName));
			reader.readLine();
			reader.readLine();
			reader.readLine();
			String line;
			while ((line = reader.readLine()) != null) {
				dayList1.add(line);
			}

			reader.close();
			
			/**
			 * The least day is a fake entity.
			 */
            for (int i=0;i<dayList1.size()-1;i++) {
				line = dayList1.get(i);
				String d = line.split(" 	")[0];				  
				  if (df.parse(d).compareTo(
						df.parse(DateUtil.getCurrentSlashDate())) < 0) {
					  dayList.add(line);
					  //System.out.println(d);

				  } else {
					 //System.out.println(d);
				  }			
				
			}
			
			BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
			StringBuffer buf = new StringBuffer();
			switch (type) {
			case TYPE_TW1000:
				writer.write(WTX0_WORD);
				break;
			case TYPE_TWX1:
				writer.write(WTX1_WORD);
				break;
			}
			for (int i = 0; i < dayList.size(); i++) {
				writer.write(dayList.get(i) + "\n");
			}

			String d = df.format(entity.startTime.getTime());

			Date tomorrow = DateUtil.getDaysAfterToday(1);
			buf.append(df.format(tomorrow) + " 	");
			buf.append(entity.ohlc.open + " 	");
			buf.append(entity.ohlc.high + " 	");
			buf.append(entity.ohlc.low + " 	");
			buf.append(entity.ohlc.close + " 	");
			buf.append(entity.volume + "\n");

			writer.write(df.format(entity.startTime.getTime()) + " 	");
			writer.write(entity.ohlc.open + " 	");
			writer.write(entity.ohlc.high + " 	");
			writer.write(entity.ohlc.low + " 	");
			writer.write(entity.ohlc.close + " 	");
			writer.write(entity.volume + "\n");

			writer.write(buf.toString());

			writer.flush();
			writer.close();
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	private void historySave2File(ArrayList<StockEntity> entities,
			String fileName, int type) {

		DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
			switch (type) {
			case TYPE_TW1000:
				writer.write(WTX0_WORD);
				break;
			case TYPE_TWX1:
				writer.write(WTX1_WORD);
				break;
			}
			StringBuffer buf = new StringBuffer();
			for (int i = 0; i < entities.size(); i++) {
				StockEntity entity = entities.get(i);
				String d = df.format(entity.startTime.getTime());
				if (i == entities.size() - 1) {
					Date tomorrow = DateUtil.getDaysAfterToday(1);
					buf.append(df.format(tomorrow) + " 	");
					buf.append(entity.ohlc.open + " 	");
					buf.append(entity.ohlc.high + " 	");
					buf.append(entity.ohlc.low + " 	");
					buf.append(entity.ohlc.close + " 	");
					buf.append(entity.volume + "\n");
				}
				writer.write(df.format(entity.startTime.getTime()) + " 	");
				writer.write(entity.ohlc.open + " 	");
				writer.write(entity.ohlc.high + " 	");
				writer.write(entity.ohlc.low + " 	");
				writer.write(entity.ohlc.close + " 	");
				writer.write(entity.volume + "\n");
			}
			writer.flush();
			writer.close();
		} catch (IOException e) {
			System.out.println(e);
		}
	}

	public static void main(String[] args) throws IOException {
		boolean getHistory = false;
		if (getHistory) {
			new DailyExec(true);

		} else {
			new DailyExec(false);
		}

	}

}